package lsem.eclipse.vdf.ui.handler;

import lsem.eclipse.vdf.ui.navigator.VDFCommonNavigatorView;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.neo4j.neoclipse.view.NeoGraphViewPart;

public class VDFCommonNavigatorHandler extends AbstractHandler implements
		IHandler {

	public static final String ID = VDFCommonNavigatorHandler.class.getCanonicalName();

	private NeoGraphViewPart graphView = null;

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		// Get the view
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
		page.addPartListener(new EditorPaneListener(page));

		VDFCommonNavigatorView vdfNavi = (VDFCommonNavigatorView) page
				.findView(VDFCommonNavigatorView.ID);
		ISelection selection = vdfNavi.getSite().getSelectionProvider()
				.getSelection();
		if (selection != null && selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			// If we had a selection lets open the editor
			if (obj instanceof IFolder) {
				 IFolder folder = (IFolder) obj;

				 String nodeName = folder.getName();
 
				try {
					this.graphView = (NeoGraphViewPart) page
							.findView(NeoGraphViewPart.ID);

					if (this.graphView != null) {
						this.graphView.showNode("label", nodeName);// setInput(node);
					}

				} catch (Exception e) {
					System.out.println(e.getStackTrace());
				}
			}
			else if (obj instanceof IFile){
				IFile file = (IFile) obj;

				 int dot = file.getName().lastIndexOf(".");
				 String nodeName = file.getName().substring(0, dot);

				try {
					this.graphView = (NeoGraphViewPart) page
							.findView(NeoGraphViewPart.ID);

					if (this.graphView != null) {
						this.graphView.showNode("label", nodeName);// setInput(node);
					}

				} catch (Exception e) {
					System.out.println(e.getStackTrace());
				}
			}
		}
		return null;
	}

}
